package com.bejoy.coolatin.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.app.Activity;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Vibrator;
import android.provider.MediaStore.Images.ImageColumns;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.NumberPicker;

import com.bejoy.coolatin.R;
import com.bejoy.coolatin.volley.ImageCacheManager;

/**
 * 通用方法，工具类
 * 
 * @author Savvy 2014.12.01
 */
public class ObtainInterfaceUtil {

	// 字符串转换为md5
	public String getMD5(String val) {
		MessageDigest md5;
		byte[] m = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
			md5.update(val.getBytes());
			m = md5.digest();// 加密
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int i;
		StringBuffer buf = new StringBuffer("");
		for (int offset = 0; offset < m.length; offset++) {
			i = m[offset];
			if (i < 0)
				i += 256;
			if (i < 16)
				buf.append("0");
			buf.append(Integer.toHexString(i));
		}
		return buf.toString();
		// return new String(m);
	}

	// bitmap转字符串
	public String getFileName(Bitmap bitmap) {
		// 内置存储卡
		String fileName = Environment.getExternalStorageDirectory().toString()
				+ File.separator + "Coolatin" + File.separator + "picture"
				+ File.separator + "repairs_" + System.currentTimeMillis()
				+ ".jpg";
		File file = new File(fileName);
		if (!file.getParentFile().exists()) {
			file.getParentFile().mkdirs(); // 创建文件夹
		}
		System.out.println(bitmap.getByteCount() + "#############");
		try {
			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(file));
			// System.out.println(bitmap.getByteCount()+"#############");
			bitmap.compress(Bitmap.CompressFormat.JPEG, 30, bos); // 向缓冲区之中压缩图片
			if (bitmap != null && !bitmap.isRecycled()) {
				bitmap.recycle();
				bitmap = null;
			}
			bos.flush();
			bos.close();
			// System.out.println(fileName+"fileName**************");
		} catch (Exception e) {
		}
		return fileName;
	}

	/**
	 * final Activity activity ：调用该方法的Activity实例 long milliseconds ：震动的时长，单位是毫秒
	 * long[] pattern ：自定义震动模式 。数组中数字的含义依次是[静止时长，震动时长，静止时长，震动时长。。。]时长的单位是毫秒
	 * boolean isRepeat ： 是否反复震动，如果是true，反复震动，如果是false，只震动一次
	 */
	public static void Vibrate(final Activity activity, long milliseconds) {
		Vibrator vib = (Vibrator) activity
				.getSystemService(Service.VIBRATOR_SERVICE);
		vib.vibrate(milliseconds);
	}

	public static void Vibrate(final Activity activity, long[] pattern,
			boolean isRepeat) {
		Vibrator vib = (Vibrator) activity
				.getSystemService(Service.VIBRATOR_SERVICE);
		vib.vibrate(pattern, isRepeat ? 1 : -1);
	}

	// 将Bitmap转换成Base64字符串
	public String bitmaptoBase64String(Bitmap bitmap) {
		String string = null;
		ByteArrayOutputStream bStream = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.JPEG, 100, bStream);
		byte[] bytes = bStream.toByteArray();
		string = Base64.encodeToString(bytes, Base64.DEFAULT);
		return string;
	}

	// 将Base64字符串转换成Bitmap类型
	public Bitmap base64StringtoBitmap(String string) {
		Bitmap bitmap = null;
		try {
			byte[] bitmapArray;
			bitmapArray = Base64.decode(string, Base64.DEFAULT);
			bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0,
					bitmapArray.length);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bitmap;

	}

	/**
	 * 字符串转文件
	 * 
	 * @param content
	 *            文件内容
	 * @param filePath
	 *            文件绝对路径
	 * @return 是否转码成功
	 */
	public boolean base64StringtoFile(String content, String filePath) {
		boolean flag = true;
		// 第一步：确定要操作的文件路径
		File file = new File(filePath);
		if (!file.getParentFile().exists()) { // 父路径不存在
			file.getParentFile().mkdirs(); // 创建目录
		}
		// 第二步：通过OutputStream的子类实例化父类，可以追加内容
		OutputStream output;
		try {
			output = new FileOutputStream(file);
			// 第三步：进行内容的输出
			byte[] fileArray;
			fileArray = Base64.decode(content, Base64.DEFAULT);
			// for (int x = 0; x < fileArray.length; x++) {
			// output.write(fileArray[x]); // 输出单个字节数据
			// }
			BufferedOutputStream bufferedOutput = new BufferedOutputStream(
					output);
			bufferedOutput.write(fileArray);
			// 第四步：关闭输出流
			bufferedOutput.close();
			output.close(); // 关闭
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		}
		return flag;
	}

	// // 文件转Base64
	// public static String encodeBase64File(String path) throws Exception {
	// File file = new File(path);
	// FileInputStream inputFile = new FileInputStream(file);
	// byte[] buffer = new byte[(int) file.length()];
	// inputFile.read(buffer);
	// inputFile.close();
	// return Base64.encodeToString(buffer, Base64.DEFAULT);
	// }
	//
	// // Base64转文件
	// public static void decoderBase64File(String base64Code, String savePath)
	// throws Exception {
	// // byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
	// byte[] buffer = Base64.decode(base64Code, Base64.DEFAULT);
	// FileOutputStream out = new FileOutputStream(savePath);
	// out.write(buffer);
	// out.close();
	// }

	// 读取音频文件返回字符串
	public static String encodeFile(String path) {
		File file = new File(path);
		FileInputStream inputFile;
		byte[] buffer = null;
		ByteArrayOutputStream arrayOutputStream = null;
		try {
			inputFile = new FileInputStream(file);
			arrayOutputStream = new ByteArrayOutputStream();
			buffer = new byte[1024 * 6];
			int ch = -1;
			while ((ch = inputFile.read(buffer)) != -1) {
				arrayOutputStream.write(buffer, 0, ch);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		byte[] data = arrayOutputStream.toByteArray();

		return android.util.Base64.encodeToString(data, Base64.DEFAULT);
	}

	/**
	 * 使用MD5算法对传入的key进行加密并返回。
	 */
	public String StringToMD5(String key) {
		String cacheKey;
		try {
			final MessageDigest mDigest = MessageDigest.getInstance("MD5");
			mDigest.update(key.getBytes());
			cacheKey = bytesToHexString(mDigest.digest());
		} catch (NoSuchAlgorithmException e) {
			cacheKey = String.valueOf(key.hashCode());
		}
		return cacheKey;
	}

	// 将md5加密的二进制转化为字符串
	private String bytesToHexString(byte[] bytes) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < bytes.length; i++) {
			String hex = Integer.toHexString(0xFF & bytes[i]);
			if (hex.length() == 1) {
				sb.append('0');
			}
			sb.append(hex);
		}
		return sb.toString();
	}

	// 网络获取图片(小图)
	public Bitmap getBitmap(String biturl) {
		Bitmap bitmap = null;
		try {
			URL url = new URL(biturl);
			URLConnection conn = url.openConnection();
			InputStream in = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(new BufferedInputStream(in));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bitmap;
	}

	// bitmao转为圆形图片
	public Bitmap createCircleImage(Bitmap source) {
		final Paint paint = new Paint();
		paint.setAntiAlias(true);
		int min = source.getWidth() <= source.getHeight() ? source.getWidth()
				: source.getHeight();
		Bitmap target = Bitmap.createBitmap(min, min, Config.ARGB_8888);
		/**
		 * 产生一个同样大小的画布
		 */
		Canvas canvas = new Canvas(target);
		/**
		 * 首先绘制圆形
		 */
		canvas.drawCircle(min / 2, min / 2, min / 2, paint);
		/**
		 * 使用SRC_IN
		 */
		paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
		/**
		 * 绘制图片
		 */
		canvas.drawBitmap(source, 0, 0, paint);
		// 回收原图
		// if(source!=null&&!source.isRecycled()){
		// source.recycle();
		// source = null;
		// }
		// System.gc();
		return target;
	}

	// 压缩图片
	public Bitmap compressBitmap(Bitmap image, int size) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		int options = 50;
		while (baos.toByteArray().length / 1024 > size) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
			baos.reset();// 重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
			options -= 10;// 每次都减少10
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
		Log.d("savvy", "图片压缩处理:" + bitmap.getWidth() + ";" + bitmap.getHeight());
		return bitmap;
	}

	/**
	 * bitmap按指定长宽压缩
	 * 
	 * @param image
	 *            原始图片
	 * @param iamgeWidth
	 *            指定宽度
	 * @param imageHeight
	 *            指定高度
	 * @return 压缩好的
	 */
	public Bitmap getBitmapByBitmap(Bitmap image, int iamgeWidth,
			int imageHeight) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.PNG, 100, baos);
		if (baos.toByteArray().length / 5012 > 1024) {// 判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
			baos.reset();// 重置baos即清空baos
			image.compress(Bitmap.CompressFormat.PNG, 50, baos);// 这里压缩50%，把压缩后的数据存放到baos中
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		// 开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		// 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
		// float imageHeight = 800f;//这里设置高度为800f
		// float iamgeWidth = 480f;//这里设置宽度为480f
		// 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;// be=1表示不缩放
		if (w > h && w > iamgeWidth) {// 如果宽度大的话根据宽度固定大小缩放
			be = (int) (newOpts.outWidth / iamgeWidth);
		} else if (w < h && h > imageHeight) {// 如果高度高的话根据宽度固定大小缩放
			be = (int) (newOpts.outHeight / imageHeight);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;// 设置缩放比例
		// 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		isBm = new ByteArrayInputStream(baos.toByteArray());
		try {
			bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
		} catch (OutOfMemoryError error) {
			if (bitmap != null && !bitmap.isRecycled()) {
				bitmap.recycle();
				bitmap = null;
			}
			System.gc();
			System.runFinalization();
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = be * 5;
			bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
		}
		return compressBitmap(bitmap, 100);// 压缩好比例大小后再进行质量压缩
	}

	/**
	 * 路径图片按指定长宽压缩
	 * 
	 * @param image
	 *            原始图片
	 * @param iamgeWidth
	 *            指定宽度
	 * @param imageHeight
	 *            指定高度
	 * @return 压缩好的
	 */
	public Bitmap getBitmapByPath(String srcPath, int iamgeWidth,
			int imageHeight) {
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		// 开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// 此时返回bm为空

		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		// 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
		// float imageHeight = 800f;//这里设置高度为800f
		// float iamgeWidth = 480f;//这里设置宽度为480f
		// 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;// be=1表示不缩放
		if (w > h && w > iamgeWidth) {// 如果宽度大的话根据宽度固定大小缩放
			be = (int) (newOpts.outWidth / iamgeWidth);
		} else if (w < h && h > imageHeight) {// 如果高度高的话根据宽度固定大小缩放
			be = (int) (newOpts.outHeight / imageHeight);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;// 设置缩放比例
		// 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		try {
			bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
		} catch (OutOfMemoryError error) {
			if (bitmap != null && !bitmap.isRecycled()) {
				bitmap.recycle();
				bitmap = null;
			}
			System.gc();
			System.runFinalization();
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = be * 5;
			bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
		}
		Log.d("savvy", "图片处理:" + w + ";" + h + ";" + newOpts.outWidth + ";"
				+ newOpts.outHeight);
		return compressBitmap(bitmap, 100);// 压缩好比例大小后再进行质量压缩
	}

	/**
	 * 隐藏或者显示 时间选择器相应的时间项
	 * 
	 * @param picker
	 *            传入一个DatePicker对象
	 * @param queryType
	 *            1：隐藏日，2：隐藏日和月
	 */
	public void hintDatePicker(DatePicker picker, int queryType) {
		// 利用java反射技术得到picker内部的属性，并对其进行操作
		try {
			Class<?> myDatePicker = Class.forName("android.widget.DatePicker");
			// 为了简单，缩写了... fd是field_day,fm是field_month。
			Field fd = null, fm = null, fy = null;
			// Field a = c.getDeclaredField("mMonthSpinner");
			// 在这里做判断，入过系统版本大于4.0，就让他执行这一块,不做判断在有的手机可能没法实现
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
				fd = myDatePicker.getDeclaredField("mDaySpinner");
				fm = myDatePicker.getDeclaredField("mMonthSpinner");
				fy = myDatePicker.getDeclaredField("mYearSpinner");
			} else {
				fd = myDatePicker.getDeclaredField("mDayPicker");
				fm = myDatePicker.getDeclaredField("mMonthPicker");
				fy = myDatePicker.getDeclaredField("mYearPicker");
			}
			// 对字段获取设置权限
			fd.setAccessible(true);
			fm.setAccessible(true);
			fy.setAccessible(true);
			// 得到对应的控件
			NumberPicker vd = (NumberPicker) fd.get(picker);
			NumberPicker vm = (NumberPicker) fm.get(picker);
			NumberPicker vy = (NumberPicker) fy.get(picker);// 暂时不隐藏年
			// Type是3表示显示年月，隐藏日,vd可以从下面提取出来的，懒的 ...o(╯□╰)o
			if (queryType == 1) {
				vd.setVisibility(View.GONE);
				vm.setVisibility(View.VISIBLE);
				// vd.setEnabled(false);
			}// Type是4代表显示年，隐藏日和月
			else if (queryType == 2) {
				// vd.setVisibility(View.GONE);
				// vm.setVisibility(View.GONE);
				vd.setEnabled(false);
				vm.setEnabled(false);
			}
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**
	 * // 根据网址，异步加载圆角图片
	 * 
	 * @param urlStr
	 *            图片地址
	 * @param image
	 *            图片控件
	 * @param circle
	 *            是否圆角
	 */
	public void loadCircleBitmap(String urlStr, ImageView image, boolean circle) {
		// Log.e("savvy", "loadCircleBitmap"+urlStr);
		AsyncImageLoader asyncLoader = new AsyncImageLoader(image,
				ImageCacheManager.getInstance(), circle);// 什么一个异步图片加载对象
		Bitmap bitmap = asyncLoader.getBitmapFromMemoryCache(urlStr);// 首先从内存缓存中获取图片
		// Log.e("savvy", String.valueOf(bitmap!=null));
		if (bitmap != null) {
			if (urlStr.equals(image.getTag())) {
				image.setImageBitmap(bitmap);// 如果缓存中存在这张图片则直接设置给ImageView
			}
		} else {
			image.setImageResource(R.drawable.ic_launcher);// 否则先设置成默认的图片
			asyncLoader.execute(urlStr);// 然后执行异步任务AsycnTask 去网上加载图片
		}
	}

	/**
	 * 定金支付，根据总价计算定金
	 * 
	 * @param sum
	 *            总价
	 * @return 定金价格
	 */
	public int getPricingForSum(float sum) {
		int pricing = 0;
		if (sum > 0 && sum <= 500) {
			pricing = (int) sum;
		} else if (sum > 500 && sum <= 5000) {
			pricing = 500;
		} else if (sum > 5000 && sum <= 10000) {
			pricing = 1000;
		} else if (sum > 10000 && sum <= 15000) {
			pricing = 1500;
		} else if (sum > 15000 && sum <= 20000) {
			pricing = 2000;
		} else if (sum > 20000 && sum <= 25000) {
			pricing = 2500;
		} else if (sum > 25000 && sum <= 30000) {
			pricing = 3000;
		} else if (sum > 30000 && sum <= 35000) {
			pricing = 3500;
		} else if (sum > 35000 && sum <= 40000) {
			pricing = 4000;
		} else if (sum > 40000 && sum <= 45000) {
			pricing = 4500;
		} else if (sum > 45000) {
			pricing = 5000;
		}

		return pricing;
	}

	// 判断miui系统版本
	@Deprecated
	public String getSystemProperty(String propName) {
		// "ro.miui.ui.version.name"
		String line;
		BufferedReader input = null;
		try {
			Process p = Runtime.getRuntime().exec("getprop " + propName);
			input = new BufferedReader(
					new InputStreamReader(p.getInputStream()), 1024);
			line = input.readLine();
			input.close();
		} catch (IOException ex) {
			Log.e("savvy", "Unable to read sysprop " + propName, ex);
			return null;
		} finally {
			if (input != null) {
				try {
					input.close();
				} catch (IOException e) {
					Log.e("savvy", "Exception while closing InputStream", e);
				}
			}
		}
		return line;
	}

	/**
	 * 根据图片uri获取路径
	 * 
	 * @param context
	 * @param uri
	 * @return the file path or null
	 */
	public static String getRealFilePath(final Context context, final Uri uri) {
		if (null == uri)
			return null;
		final String scheme = uri.getScheme();
		String data = null;
		if (scheme == null)
			data = uri.getPath();
		else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
			data = uri.getPath();
		} else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
			Cursor cursor = context.getContentResolver().query(uri,
					new String[] { ImageColumns.DATA }, null, null, null);
			if (null != cursor) {
				if (cursor.moveToFirst()) {
					int index = cursor.getColumnIndex(ImageColumns.DATA);
					if (index > -1) {
						data = cursor.getString(index);
					}
				}
				cursor.close();
			}
		}
		return data;
	}

	/**
	 * 读取图片的旋转的角度
	 * 
	 * @param path
	 *            图片绝对路径
	 * @return 图片的旋转角度
	 */
	public int getBitmapDegree(String path) {
		int degree = 0;
		try {
			// 从指定路径下读取图片，并获取其EXIF信息
			ExifInterface exifInterface = new ExifInterface(path);
			// 获取图片的旋转信息
			int orientation = exifInterface.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				degree = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				degree = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				degree = 270;
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return degree;
	}

	public Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
		Bitmap returnBm = null;

		// 根据旋转角度，生成旋转矩阵
		Matrix matrix = new Matrix();
		matrix.postRotate(degree);
		try {
			// 将原始图片按照旋转矩阵进行旋转，并得到新的图片
			returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
					bm.getHeight(), matrix, true);
		} catch (OutOfMemoryError e) {
		}
		if (returnBm == null) {
			returnBm = bm;
		}
		if (bm != returnBm) {
			bm.recycle();
		}
		return returnBm;
	}
}
